package jdbc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA
 * Description:JDBC控制事务学习
 * User:22954
 * Date:2024-05-15
 * Time:21:23
 */
public class Transaction {
    /*
    JDBC默认执行每个sql语句后直接commit
    connection.setAutoCommit(false)  取消自动提交
    void rollback()
    Savepoint setSavepoint()
    void commit()
     */
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src/jdbc/mysql.properties"));
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
            String sql1 = "update `account` set balance = balance - 100 where id = 1";
            String sql2 = "update `account` set balance = balance + 100 where id = 2";
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();
//            int i = 1 / 0;
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            System.out.println("执行异常,回滚sql");
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            e.printStackTrace();
        } finally {
            try {
                connection.commit();
                preparedStatement.close();
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
